package com.kigkrazy.kiutils;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;


//共享文件操作的封装，对文件加锁，以防止文件操作影响
public class SharedFileUtils {
	public static boolean writeFile(File file, String content){
		int i = 0;
        try {
            if (!file.exists())
            	file.createNewFile();

            RandomAccessFile out = new RandomAccessFile(file, "rw");
            FileChannel fcout = out.getChannel();
            FileLock flout = null;
            //循环五次尝试请求文件锁
            while (i < 5) {
                try {
                    flout = fcout.tryLock();
                    i++;
                    break;
                } catch (Exception e) {
                    Thread.sleep(1000);
                    i++;
                }
            }
            if(null == flout){
            	out.close();
            	fcout.close();
            	return false;
            }
            out.write(content.getBytes("utf-8"));
            flout.release();
            fcout.close();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
	}
	

	public static String readFile(File file) {
		int i = 0;
		try {
			if (!file.exists())
				return "";

			RandomAccessFile in = new RandomAccessFile(file, "rw");
			FileChannel fcin = in.getChannel();
			FileLock flin = null;
			//轮询五次尝试获取文件锁
			while (i < 5) {
				try {
					flin = fcin.tryLock();
					i++;
					break;
				} catch (Exception e) {
					Thread.sleep(1000);
					i++;
				}
			}
			
			if(null == flin){
				fcin.close();
				in.close();
				return "";
			}

			int len = (int) in.length();
			byte[] buf = new byte[len];
			in.read(buf);
			String str = new String(buf);
			flin.release();
			fcin.close();
			in.close();
			return str;
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		} catch (InterruptedException e) {
			e.printStackTrace();
			return "";
		}
	}
}
